import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { FetchService } from '../../../../core/net/fetch.service';
import * as moment from 'moment';
import { UtilService } from '../../../../core/util/util.service';

const tableHeadHash = {
    'val1': '唐徕渠',
    'val2': '汉延渠',
    'val3': '惠农渠',
    'val4': '西干渠',
    'val5': '大清渠',
    'val6': '总干直开口',
    'val7': '泰民渠',
    'val8': '秦渠',
    'val9': '汉渠',
    'val10': '马莲渠',
    'val11': '东干渠',
    'val12': '七星渠',
    'val13': '跃进渠',
    'val14': '泉眼山',
    'val15': '大战场',
    'val16': '美利渠',
    'val17': '寿渠',
    'val18': '角渠',
    'val19': '盐环定',
    'val20': '红寺堡一泵站',
    'val21': '固海扩灌',
    'val22': '红寺堡水源泵站',
    'val23': '惠农渠扬水',
    'val24': '宁东水源泵站',
    'val25': '七星渠退水'
};
const cardHash = {
    'val1': '唐徕渠管理处',
    'val2': '西干渠管理处',
    'val3': '惠农渠管理处',
    'val4': '汉延渠管理处',
    'val5': '秦汉渠管理处',
    'val6': '渠首管理处',
    'val7': '七星渠管理处',
    'val8': '宁西公司',
    'val9': '中卫市沙坡头区水务局',
    'val10': '固海扬水管理处',
    'val11': '红寺堡扬水管理处',
    'val12': '盐环定扬水管理处'
};
const intlCardData = {
    'val1': '-',
    'val2': '-',
    'val3': '-',
    'val4': '-',
    'val5': '-',
    'val6': '-',
    'val7': '-',
    'val8': '-',
    'val9': '-',
    'val10': '-',
    'val11': '-',
    'val12': '-',
    'val13': '-'
};

@Component({
    selector: 'app-wt-canal-flow',
    templateUrl: './wt-canal-flow.component.html',
    styleUrls: ['./wt-canal-flow.component.scss']
})
export class WtCanalFlowComponent implements OnInit {
    searchForm: FormGroup;
    currentCardId = 'val13';
    currentTotalId = 'totalVal13';
    subCardList = [];
    basicLineOpts: any = {
        title: {
            text: '累计引水过程线',
            x: 'center',
            textStyle: {
                color: '#777',
                fontSize: 16
            }
        },
        color: ['#ddb00a', '#3398DB'],
        grid: {
            top: '10%',
            left: '3%',
            right: '4%',
            bottom: '8%',
            containLabel: true
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
        },
        yAxis: {
            name: '流量(m³/s)',
            type: 'value'
        }
    };
    totalData: any = intlCardData;
    planTotalData: any = intlCardData;
    oldTotalData: any = intlCardData;
    actualChartData = [];
    planChartData = [];
    drainChartOpts: any = {};
    tableHead = [];
    widthConfig = ['150px', '80px'];
    tableData: Array<any> = [];
    waterTotalList: Array<any> = [];
    flowTotalList: Array<any> = [];
    loading = false;

    constructor(private fb: FormBuilder,
                private util: UtilService,
                private message: NzMessageService,
                private fetchService: FetchService) {
        this.searchForm = this.fb.group({
            rangePickerTime: [[moment().subtract(1, 'months').startOf('month').valueOf(), new Date()]]
        });
    }

    ngOnInit(): void {
        this.tableHead = Object.keys(tableHeadHash).map(key => {
            this.widthConfig.push('80px');
            return {
                id: key,
                name: tableHeadHash[key]
            };
        });
        this.subCardList = Object.keys(cardHash).map((key, idx) => {
            return {
                id: key,
                totalId: `totalVal${idx + 1}`,
                name: cardHash[key]
            };
        });
        this.queryInfo();
    }

    getTableData(): void {
        this.loading = true;
        this.fetchService.post('base/wrsReportDay/dateListAll', {
            stDate: moment(this.searchForm.value.rangePickerTime[0]).format('YYYY-MM-DD'),
            edDate: moment(this.searchForm.value.rangePickerTime[1]).format('YYYY-MM-DD')
        }).subscribe(res => {
            if (Array.isArray(res)) {
                this.tableData = res;
                this.loading = false;
                this.calcTableData();
            }
        });
    }

    queryInfo(): void {
        const params = {
            stDate: moment(this.searchForm.value.rangePickerTime[0]).format('YYYY-MM-DD'),
            edDate: moment(this.searchForm.value.rangePickerTime[1]).format('YYYY-MM-DD')
        };
        this.fetchService.post('base/wrsReportDayManage/dateListAll', params).subscribe(res => {
            // if (res['total']) {this.totalData = res['total'];}
            // if (res['planTotal']) {this.planTotalData = res['planTotal'];}
            // if (res['oldTotal']) {this.oldTotalData = res['oldTotal'];}
            this.totalData = res['total'] || intlCardData;
            this.planTotalData = res['planTotal'] || intlCardData;
            this.oldTotalData = res['oldTotal'] || intlCardData;
            this.actualChartData = res['list'] || [];
            this.planChartData = res['planList'] || [];
            this.cardSelectionChanged(this.currentCardId, this.currentTotalId, cardHash[this.currentCardId]);
        });
        this.getTableData();
    }

    cardSelectionChanged(id, totalId, title = '引黄灌区'): void {
        this.currentCardId = id;
        this.currentTotalId = totalId;
        this.drainChartOpts = {
            title: {
                text: `${title}累计引水过程线`
            },
            legend: {
                bottom: 0,
                data: ['计划累计水量', '实际累计水量']
            },
            yAxis: {
                name: '水量(亿m³)'
            },
            xAxis: {
                data: this.planChartData.map(item => {
                    return item['date'];
                })
            },
            series: [
                {
                    name: '计划累计水量',
                    type: 'line',
                    smooth: true,
                    data: this.planChartData.map(item => {
                        return item[totalId];
                    })
                },
                {
                    name: '实际累计水量',
                    type: 'line',
                    smooth: true,
                    data: this.actualChartData.map(item => {
                        return item[totalId];
                    })
                }
            ]
        };
    }

    private calcTableData() {
        this.tableHead.forEach((obj, i) => {
            const colData = this.util.getItemValues(this.tableData, obj.id, true);
            this.flowTotalList[i] = this.keepTwoDecimalFull(this.util.sum(colData));
            this.waterTotalList[i] = this.getWaterByFlow(this.flowTotalList[i]);
        });
    }

    isCardActivated(id): boolean {
        return this.currentCardId === id;
    }

    /**
     * 根据流量数据计算水量
     * 公式：水量（万m³） = 流量（m³/s） * 8.64
     */
    getWaterByFlow(flow: number, day = 1): string {
        return this.keepTwoDecimalFull(flow * day * 8.64);
    }

    // 强制补齐 小数位数
    keepTwoDecimalFull(x, num = 2): string {
        const f = Math.round(x * 100) / 100;
        let s = f.toFixed(num);
        let rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + num) {
            s += '0';
        }
        return s;
    }
}
